class UserController {

    def index = {
        redirect(action:login)
    }

    def login = {
        if (!params.email)
            return
        
        def userInstance = User.findByEmail(params.email)

        if(!userInstance) {
            flash.message = "User not found with email ${params.email}"
        }
        else {
            session.user = userInstance
            redirect(controller:'dashboard', action:'index')
        }
    }

    def logout = {
        session.user = null
    }

    
    def list = {
        /*
        TODO:
        관리자만 접근할 수 있도록 권한주기? 관리자는 아이디보고 매칭시키기 해버려...
        password안보이도록 하기
        계획리스트에 나라 이름 뜨도록 바꾸기
        리스트에서 삭제버튼 누르면 삭제하고 화면갱신
        */
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ userInstanceList: User.list( params ), userInstanceTotal: User.count() ]
    }

    def delete = {
        /*
        TODO:
        하위 항목까지 검색해서 지우기
        */
        def userInstance = User.get( params.id )
        if(userInstance) {
            try {
                userInstance.delete()
                flash.message = "User ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "User ${params.id} could not be deleted"
                redirect(action:list,id:params.id)
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        /*
        TODO:
        암호필드는 비운 상태로 생성
        계획 리스트는 수정이 불가능하도록 바꾸기
        */
        def userInstance = User.get( params.id )

        if(!userInstance) {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ userInstance : userInstance ]
        }
    }

    def update = {
        def userInstance = User.get( params.id )
        if(userInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(userInstance.version > version) {

                    userInstance.errors.rejectValue("version", "user.optimistic.locking.failure", "Another user has updated this User while you were editing.")
                    render(view:'edit',model:[userInstance:userInstance])
                    return
                }
            }
            userInstance.properties = params
            if(!userInstance.hasErrors() && userInstance.save()) {
                flash.message = "User ${params.id} updated"
                redirect(action:list)
            }
            else {
                render(view:'edit',model:[userInstance:userInstance])
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def userInstance = new User()
        userInstance.properties = params
        return ['userInstance':userInstance]
    }
    def join = {
        def userInstance = new User()
        userInstance.properties = params
        return ['userInstance':userInstance]
    }

    //TODO:이거 하나로 합칠 수 있으면 좋을련만...
    def saveByAdmin = {
        def userInstance = new User(params)
        if(!userInstance.hasErrors() && userInstance.save()) {
            flash.message = "User ${userInstance.name} created"
            redirect(action:list)
        }
        else {
            render(view:'create',model:[userInstance:userInstance])
        }
    }
    def saveByUser = {
        def userInstance = new User(params)
        if(!userInstance.hasErrors() && userInstance.save()) {
            Plan defalutPlan = new Plan(name:"DefaultPlan", travelCountry:usa)
            defalutPlan.save()
            user.addToPlans(defalutPlan)
            flash.message = "User ${userInstance.name} created"
            redirect(action:login)
        }
        else {
            render(view:'join',model:[userInstance:userInstance])
        }
    }
}
